import PrinterJobs from './common/print/printerjobs.js'
import printerUtil from './common/print/printerutil.js'
import util from './common/print/util.js'
import drawQrcode from './common/print/weapp.qrcode.esm.js'
import Bluetooth from './common/print/bluetooth.js'

let bluetooth = new Bluetooth();

var base = require('../../utils/lang.js');
const _ = base._

Page({

  /**
   * 页面的初始数据
   */
  data: {
    _t: base._t(),
    isOpenBle: false, //是否已经打开蓝牙，默认为false
    devicesList: [], //设备列表
    serviceList: [], //服务列表
    deviceId: "", //选中的deviceId
    canvas_width: 240,
    canvas_height: 240,
  },

  //搜索周边设备
  startBluetoothDeviceDiscovery() {
    wx.showLoading({
      title: '蓝牙搜索中'
    })

    let self = this;
    self.devicesList = [];

    setTimeout(() => {
      wx.startBluetoothDevicesDiscovery({
        success: res => {
          wx.hideLoading();
          wx.onBluetoothDeviceFound(devices => {
            console.log("发现设备: " + JSON.stringify(devices));
            let { devicesList } = this.data
            //不重复,就添加到devicesList中,
            if (!devicesList.some(item => {
                return item.deviceId === devices.devices[0].deviceId
              })) {
              console.log(devices.devices)
              devicesList.push(devices.devices[0])
            }
            this.setData({ devicesList })
          });
        },
        fail: res => {
          wx.hideLoading();
          self.showToast(`搜索设备失败` + JSON.stringify(err));
        }
      })
    }, 200)
  },

  //停止搜索蓝牙设备
  stopBluetoothDevicesDiscovery() {
    wx.hideLoading();
    bluetooth.stopBluetoothDevicesDiscovery();
  },


  //选中设备
  async select_deviceId(e) {
    let { item } = e.currentTarget.dataset
    this.deviceId = item.deviceId;
    bluetooth.deviceId = item.deviceId;
    wx.setStorageSync('deviceId', bluetooth.deviceId);

    try {
      //1.链接设备
      let result = await bluetooth.createBLEConnection();
      //2.寻找服务
      let result2 = await bluetooth.getBLEDeviceServices();

      console.log("获取服务: " + JSON.stringify(result2));

      this.setData({
        serviceList:result2
      })

    } catch (e) {
      //TODO handle the exception
      console.log("e: " + JSON.stringify(e));
    }
  },

  //选中服务
  async select_service(e) {
    let res =  e.currentTarget.dataset.item
    bluetooth.serviceId = res.uuid;
    wx.setStorageSync('serviceId', res.uuid);

    try {
      let result = await bluetooth.getBLEDeviceCharacteristics();
    } catch (e) {
      //TODO handle the exception
      console.log("e: " + JSON.stringify(e));
    }

  },

  //打印一次
  pickUpOnce() {
    bluetooth.notifyBLECharacteristicValue();
    let self = this;
    setTimeout(() => {
      self.writeBLECharacteristicValue();
    }, 500);
  },



  //写入控制命令
  async writeBLECharacteristicValue() {

    console.log('zcj1')

    let Qrcode_res = await this.get_Qrcode();

    console.log('zcj')
    console.log(Qrcode_res);

    let printerJobs = new PrinterJobs();

    printerJobs
      .print(util.formatTime(new Date()))
      .print(printerUtil.fillLine())
      .setAlign('ct')
      .setSize(2, 2)
      .print('#zcj king')
      .setSize(1, 1)
      .print('杨洁莹loving')
      .setSize(2, 2)
      .print('在线支付(已支付)')
      .setSize(1, 1)
      .print('订单号：5415221202244734')
      .print('下单时间：' + util.formatTime(new Date()))
      .setAlign('lt')
      .print(printerUtil.fillAround('一号口袋'))
       
    for (var i = 0; i < 10; i++){ 
          console.log(i)
          printerJobs
          .print(printerUtil.inline('意大利茄汁一面 * 1', '15'))
    }
    
    
    printerJobs
    .print(printerUtil.fillAround('其他'))
    .setAlign('lt')
    .print('餐盒费：1')
    .print('[赠送康师傅冰红茶] * 1')
    .print(printerUtil.fillLine())
    .setAlign('rt')
    .print('原价：￥16')
    .print('总价：￥16')
    .setAlign('lt')
    .print(printerUtil.fillLine())
    .print('备注')
    .print("无")
    .print(printerUtil.fillLine())
    .printQrcode(Qrcode_res)
    .println();

    //console.log(printerJobs);

    let buffer = printerJobs.buffer();

    this.printbuffs(buffer);
  },

  printbuffs(buffer) {
    // 1.并行调用多次会存在写失败的可能性
    // 2.建议每次写入不超过20字节
    // 分包处理，延时调用
    const maxChunk = 20;
    const delay = 20;
    for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
      let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length);
      setTimeout(this.printbuff, j * delay, subPackage);
    }
  },

  printbuff(buffer) {
    bluetooth.writeBLECharacteristicValue(buffer);
  },

  get_Qrcode() {
    let self = this;
    return new Promise((resolve, reject) => {
      const ctx = wx.createCanvasContext('shareCanvas');
      console.log(self.canvas_width);
      ctx.clearRect(0, 0, self.canvas_width, self.canvas_height);
      
      const { canvas_width,canvas_height } = this.data

      drawQrcode({
        canvasId: 'shareCanvas',
        text: String('只是因为你'),
        width: canvas_width,
        height: canvas_height,
        callback(e) {
          setTimeout(() => {
            // 获取图片数据
            wx.canvasGetImageData({
              canvasId: 'shareCanvas',
              x: 0,
              y: 0,
              width: canvas_width,
              height: canvas_height,
              success(res) {
                resolve(util.zip_image(res));
              }
            })
          }, 1000);
        }
      });
    });
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        console.log('当前位置的经度：' + res.longitude);
        console.log('当前位置的纬度：' + res.latitude);
      }
    });

    bluetooth.openBluetoothAdapter();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})